#
# Cookbook Name:: om
# Recipe:: setupmq
# Installs the MQ Server and sets up the queue manager and queues needed for OMS
#
# Copyright 2013, IBM Corporation
#
# All rights reserved - Do Not Redistribute
#

include_recipe "gitclientsetup::default"
include_recipe "java7::install"
include_recipe "mq::install"

class Chef::Recipe
include Orchestrate
end 

zkep = "#{node[:zookeeper][:ip]}:#{node[:zookeeper][:port]}"
chef_gem 'zk' 

startinstr "Setup MQ Qmgr, Queues and JNDI Entries for OM"

bash "Set permissions on mq executables." do
    user "root"
    group "root"
    cwd "/opt/mqm/java/bin"
    code <<-EOH
        #chown -R mqm #{node[:mq][:installDir]}/bin/*
        chmod a+x #{node[:mq][:installDir]}/bin/strmqm
        chmod a+x #{node[:mq][:installDir]}/bin/runmqsc
        chmod a+x #{node[:mq][:installDir]}/bin/crtmqm
        chmod a+x #{node[:mq][:installDir]}/bin/runmqlsr
        chmod a+x #{node[:mq][:installDir]}/bin/dspmq
    EOH
end

include_recipe "was::createusergroup"
bash "add wasuser to mqm group" do
  user "root"
  code <<-EOH
    usermod -a -G mqm wasuser
  EOH
end


`(#{node[:mq][:installDir]}/bin/dspmq | grep #{node[:om][:omqmgr]})`
if  $? != 0
	bash "Create Queue Manager" do
		user "root"
		cwd "/opt/mqm"
		code <<-EOH
			su mqm -c "#{node[:mq][:installDir]}/bin/crtmqm #{node[:om][:omqmgr]}"
		EOH
	end
end

bash "Setup channels" do
  user "root"
  cwd "/opt/mqm"
  creates "/tmp/channels-setup.done"
  code <<-EOH
    #before starting the qmgr,  let's set the MaxChannels and stuff...
    echo "CHANNELS:" >> /var/mqm/qmgrs/#{node[:om][:omqmgr]}/qm.ini
    echo "   MaxChannels=1000" >> /var/mqm/qmgrs/#{node[:om][:omqmgr]}/qm.ini
    echo "   MaxActiveChannels=1000" >> /var/mqm/qmgrs/#{node[:om][:omqmgr]}/qm.ini
    echo "   ClientIdle=300 " >> /var/mqm/qmgrs/#{node[:om][:omqmgr]}/qm.ini
    touch "/tmp/channels-setup.done"
  EOH
end

`(#{node[:mq][:installDir]}/bin/dspmq | grep #{node[:om][:omqmgr]}| grep Running)`
if $? != 0
	bash "Start Queue Manager" do
		user "root"
		cwd "/opt/mqm"
		code <<-EOH
			su mqm -c "#{node[:mq][:installDir]}/bin/strmqm #{node[:om][:omqmgr]}"			
		EOH
	end
end

deployment=node[:deployment]

ruby_block "Publishing Queue Manager Status to ZooKeeper." do
    block do
        i_url = "/deployments/" + deployment + "/config/om/mqm/#{node[:fqdn]}/qmgr/status"
        dep = Dependency.new(i_url, node[:client][:status], zkep)
        dep.publish!
    end
end

mqhost=""
search(:node, "deployment:#{deployment}").each do |anode|
    if anode.role?("om_mq")
        mqhost = anode[:fqdn]
    end
end

if mqhost == ""
    raise "OMS MQ Host node not available !"
end

template "/tmp/createqueues.txt" do
    source "createqueues.txt.erb"
    owner "mqm"
    variables :ommqhost =>  mqhost, :omqmgr =>  node[:om][:omqmgr], :build_queues=> node[:common][:queueList].split(',')
    action :create
end

#  TODO:  This might be a good candidate for Zoo keeper check...
#     only create queues one time ...
bash "Create Queues for OMS" do
	user "root"		
	cwd "/opt/mqm/"
	code <<-EOH
		su mqm -c "#{node[:mq][:installDir]}/bin/runmqsc #{node[:om][:omqmgr]} < /tmp/createqueues.txt" > /tmp/queuecreation.log 2>&1
	EOH
end


template "/tmp/createjndiresources.scp" do
	source "createjndiresources.scp.erb"
	owner "mqm"
	variables(
            :ommqhost =>  mqhost,
            :qmgr =>  node[:om][:omqmgr],
            :qmgrport =>  node[:om][:omqmgrport],
            :build_queues=> node[:common][:queueList].split(',')
			)
	action :create
end


cookbook_file "/tmp/jmsadminredirect.sh" do
	source "jmsadminredirect.sh"
	user "mqm"
	owner "mqm"
	action :create
end

# MQ Java JMSAdmin does a lot of really goofy things.
#  1.  the file permissions on the directory dont' allow mq user to create files where we would need.
#  2.  the configuration file and the script that you run to create the bindings are both not write-able by mqm
# Additionally, gonna need to replace /C:/JNDI-Directory in JMSAdmin.config with a valid unix path
#  and add some jars and stuff to the script.  God only knows why they ship completely not functional scripts wiht their product.
#  3.  seems like maybe it does not work unless you run it form /opt/mqm/java/bin dir where it resides...
#TODO:  CONDITIONAL

#`cat /tmp/JNDI/.bindings | grep SCHEDULE`
#TODO:  Some condition here to make sure we only do this once...
bash "Setup JMS Admin" do
	user "mqm"
	group "mqm"
	cwd "/opt/mqm/java/bin"
	code <<-EOH
		set -x
		mkdir -p /tmp/JNDI
		chmod u+rw #{node[:mq][:installDir]}/java/bin
		chmod u+rw #{node[:mq][:installDir]}/java/bin/JMSAdmin.config  
		chmod u+rwx #{node[:mq][:installDir]}/java/bin/JMSAdmin 
		sed -i 'sX/C:/JNDI-DirectoryX/tmp/JNDIX' #{node[:mq][:installDir]}/java/bin/JMSAdmin.config
		sed -i '/java/ i\
		MQM_LIB=/opt/mqm/java/lib\\nJAVA_HOME=#{node['java7']['installDir']}\\nPATH=$JAVA_HOME/bin:$PATH\\nCLASSPATH=${MQM_LIB}/fscontext.jar\\nCLASSPATH=${MQM_LIB}/com.ibm.mqjms.jar\\nCLASSPATH=${CLASSPATH}:${MQM_LIB}/com.ibm.mqjms.jar\\nCLASSPATH=${CLASSPATH}:${MQM_LIB}/com.ibm.mq.jar\\nCLASSPATH=${CLASSPATH}:${MQM_LIB}/jms.jar\\nCLASSPATH=${CLASSPATH}:${MQM_LIB}/providerutil.jar\\nCLASSPATH=${CLASSPATH}:${MQM_LIB}/jndi.jar\\nexport CLASSPATH\\nexport PATH\\nexport JAVA_HOME'  #{node[:mq][:installDir]}/java/bin/JMSAdmin
	
		chmod +x /tmp/jmsadminredirect.sh
		mv /tmp/jmsadminredirect.sh /opt/mqm/java/bin/jmsadminredirect.sh
		/opt/mqm/java/bin/jmsadminredirect.sh

		chmod -R 755 /tmp/JNDI
	
		set +x
	
	EOH
end

#TODO:  Condition seems unreliable....
# not checking might cost time,  but doesn't hurt anything i think.
`ps -efla |grep runmqlsr |grep #{node[:om][:omqmgr]}`
#if $? != 0
	bash "Start MQ Listener" do
		user "mqm"
		group "mqm"
		cwd "/opt/mqm/"
		code <<-EOH
			nohup /opt/mqm/bin/runmqlsr  -m #{node[:om][:omqmgr]} -t TCP -p #{node[:om][:omqmgrport]} &
		EOH
	end
#end

bash "Open MQ Listener port" do
	user "root"
	code <<-EOH
		/sbin/iptables -A INPUT -p tcp --dport #{node[:om][:omqmgrport]} -j ACCEPT
		service iptables save
	EOH
end

ruby_block "Publishing MQLSR status to ZooKeeper." do 
    block do
        i_url = "/deployments/" + deployment + "/config/om/mqm/listener/status"
        dep = Dependency.new(i_url, node[:client][:status], zkep)
        dep.publish!
    end
end



cuser = node[:chef][:user]
cgroup = node[:chef][:group]
bash "Upload bindings file for mq clients (agents and services)" do
	user cuser
	group cgroup
	cwd "/tmp/"
	code <<-EOH
		ssh #{node[:common][:scpuser]}@#{node[:common][:scpip]} "mkdir -p #{node[:common][:scp_repo_dir]}/generated/#{deployment}/OM_JNDI"
		scp /tmp/JNDI/.bindings #{node[:common][:scpuser]}@#{node[:common][:scpip]}:#{node[:common][:scp_repo_dir]}/generated/#{deployment}/OM_JNDI/.bindings
	EOH
end  

stopinstr "Setup MQ Qmgr, Queues and JNDI Entries for OM"



